import { Http } from "@/core/api/http.service";
import { CacheService } from "@/core/cache/cache.service";
import { Helper } from "@/core/helper/helper.service";
import { RouterService } from "@/core/router/route.service";
import { defineStore } from "pinia";
import { pinia } from "..";
import { GlobalStoreEnum } from "../enum";
import { IOauth2TokenState, IUser } from "../interface";
/** 初始化用户信息 */
const initUser = {
  userId: "",
  username: "",
  nickName: ""
};

export const useUser = defineStore(GlobalStoreEnum.USER, {
  state: () => ({
    user: CacheService.of().get<IUser>(GlobalStoreEnum.USER) || initUser,
    logouting: false
  }),

  getters: {
    getUser(state): IUser {
      return state.user?.userId
        ? state.user
        : CacheService.of().get(GlobalStoreEnum.USER) || initUser;
    },

    nickName(state) {
      return state.user.nickName;
    },
    userId(state) {
      return state.user.userId;
    }
  },

  actions: {
    setUser(data: IUser) {
      Object.keys(data).forEach(k => {
        this.user[k] = data[k];
      });
    },
    async logout() {
      if (!this.logouting) {
        this.logouting = true;
        const router = RouterService.of().router;
        Http.of()
          .get("/lc-oauth/oauth2/logout")
          .finally(() => {
            this.clearTokenAndUser();
            let recuritUrl = window.location.hash.replace("#", "");
            if (recuritUrl.startsWith("/login")) {
              recuritUrl = "";
            }
            router
              .replace({
                path: "/login",
                query: recuritUrl
                  ? {
                      recurit_url: encodeURI(recuritUrl)
                    }
                  : null
              })
              .finally(() => {
                this.logouting = false;
              });
          });
      }
    },
    setOauth2Params(r: IOauth2TokenState) {
      CacheService.of().setToken(r.access_token);
      CacheService.of().setRefreshToken(r.refresh_token);
      CacheService.of().setTokenType(r.token_type);
    },
    clearTokenAndUser() {
      this.user = initUser;
      CacheService.of()
        .delToken()
        .delRefreshToken()
        .delete(GlobalStoreEnum.USER);
    },
    showWarning(message: string, logout = true) {
      Helper.showMessage(message, "warning");
      if (logout) this.logout();
    }
  }
});

export const useUserHooks = () => {
  return useUser(pinia);
};
